package com.cpkso.buss.backend.user.web;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cpkso.buss.backend.user.domain.User;
import com.cpkso.buss.backend.user.service.UserService;
import com.cpkso.buss.backend.user.validator.LoginValidator;
import com.cpkso.buss.backend.user.vo.LoginVo;
import com.runze.base.web.BaseController;
import com.runze.base.web.Response;

/**
 * @author wrzhxy@qq.com
 * @date 2018年3月26日
 */
@RestController
@RequestMapping(("/account"))
public class LoginController extends BaseController {
	/**
	 * 注册
	 */
	@PostMapping("/signup")
	public Response signup(@ModelAttribute User user) {
		user.setVerify(0);
		userService.create(user);
		return success();
	}
	
	/**
	 * 登录
	 * 
	 * 将登录信息放入session用于数据域为个人时权限判定
	 * TODO Response
	 * @param vo
	 * @param errors
	 * @return
	 */
	@PostMapping("/login")
	public Response login(@ModelAttribute LoginVo vo, BindingResult errors, HttpSession session) {
		LoginValidator loginValidator = new LoginValidator();
		loginValidator.validate(vo, errors);

        if( errors.hasErrors() ) {
            return failure("login validate failed");
        }
        
		Subject currentUser = SecurityUtils.getSubject();
		// ip, login time
//		Session session = currentUser.getSession();
		
		if (!currentUser.isAuthenticated()) {
		    UsernamePasswordToken token = new UsernamePasswordToken(vo.getUsername(), vo.getPassword());
		    token.setRememberMe(vo.isRememberMe());
		    try {
		        currentUser.login(token);
System.out.println("登录成功");
		        // 获取用户
		        Response response = userService.findByNameAndValid(vo.getUsername());
		        User user = (User) response.getData();
		        session.setAttribute("user", user.getId());
		        
		        return success();
		    } catch (UnknownAccountException uae) {
		        System.out.println("There is no user with username of " + token.getPrincipal());
		    } catch (IncorrectCredentialsException ice) {
		        System.out.println("Password for account " + token.getPrincipal() + " was incorrect!");
		    } catch (LockedAccountException lae) {
		        System.out.println("The account for username " + token.getPrincipal() + " is locked.  " +
		                "Please contact your administrator to unlock it.");
		    }
		    // ... catch more exceptions here (maybe custom ones specific to your application?
		    catch (AuthenticationException ae) {
		        //unexpected condition?  error?
		    	System.out.println("else");
		    }
		    return failure("登录失败");
		}
System.out.println("登录步骤完成");
		// 已经处于登录成功的状态
		return success();
	}
	@RequestMapping("/welcome")
	public Response welcome() {
		return success();
	}
	@RequestMapping("/403")
	public Response forbidden() {
		return failure("账户或密码错误", 403);
	}
	@RequestMapping("/logout")
    public Response logout() {
        SecurityUtils.getSubject().logout();
        return success();
    }
	
	@Autowired
	private UserService userService;
}
